package com.psct.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.psct.Constant;
import com.psct.PSCTUtil;
import com.psct.R;
import com.psct.ThreadPool;
import com.psct.bean.Criticism;
import com.psct.bean.UserAccount;
import com.psct.social.SocialAccount.SendResultListener;
import com.psct.social.SocialManager;
import com.psct.social.SocialManager.OnBindListener;
import com.psct.social.UserAccountManager;
import com.psct.web.HttpUtil;

public class AddCriticismActivity extends SherlockActivity implements TextWatcher, OnClickListener {

	/**
	 * 新浪腾讯绑定图标
	 */
	private ImageView ivSina, ivTence;
	private Button btnSend;
	private EditText etContent;
	private TextView tvSize, tvLimit;
	private int textId;
	private ProgressDialog progress;
	private SocialManager sm;
	private boolean isSinaBind, isTenceBind;
	private List<String> imagePathList;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MESSAGE_SEND_OK:
				Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
				break;
			case Constant.MESSAGE_SEND_SINA_OK:
				Toast.makeText(getApplicationContext(), "同步到新浪微博成功", Toast.LENGTH_SHORT).show();
				break;
			case Constant.MESSAGE_SEND_TENCE_OK:
				Toast.makeText(getApplicationContext(), "同步到腾讯微博成功", Toast.LENGTH_SHORT).show();
				break;
			case Constant.MESSAGE_NET_ERR:

				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar actionBar = this.getSupportActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.actionbar_bg));
		this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		this.setContentView(R.layout.activity_add_critism);
		// 获得课文id
		textId = this.getIntent().getIntExtra("textId", -1);
		imagePathList = this.getIntent().getStringArrayListExtra("imagePathList");
		initUI();
		initSocial();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	/**
	 * 初始化UI
	 */
	protected void initUI() {
		etContent = (EditText) this.findViewById(R.id.et_content);
		etContent.addTextChangedListener(this);

		btnSend = (Button) this.findViewById(R.id.btn_send);
		btnSend.setOnClickListener(this);

		ivSina = (ImageView) this.findViewById(R.id.iv_sina);
		ivSina.setOnClickListener(this);
		ivTence = (ImageView) this.findViewById(R.id.iv_tence);
		ivTence.setOnClickListener(this);

		tvLimit = (TextView) this.findViewById(R.id.tv_limit);
	}

	/**
	 * 初始化社交帐号
	 */
	private void initSocial() {
		sm = SocialManager.getInstance(this.getApplicationContext());
		isSinaBind = sm.isSinaBinded();
		isTenceBind = sm.isTenceBinded();
		ivSina.setImageResource(isSinaBind ? R.drawable.sina_ico : R.drawable.sina_ico_unbind);
		ivTence.setImageResource(isTenceBind ? R.drawable.tence_ico : R.drawable.tence_ico_unbind);

	}

	/**
	 * 发送评论
	 */
	private void send(final String content) {
		progress = new ProgressDialog(this);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
		progress.setTitle("正在发送……");// 设置标题
		// progress.setIcon(R.drawable.icon);//设置图标
		// progress.setMessage("这是一个圆形进度条");
		progress.setIndeterminate(true);// 设置进度条是否为不明确
		progress.setCancelable(false);// 设置进度条是否可以按退回键取消
		progress.show();
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String result = new HttpUtil(getApplicationContext()).addCriticism("-1", textId,
						content);
				if (result != null && result.equals("0")) {
					// 发送成功
					Criticism criticism = new Criticism();
					criticism.date = new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date());
					UserAccount user = UserAccountManager.getInstance().getUser(
							getApplicationContext());
					if (user != null) {
						criticism.user = user.userName;
					} else {
						criticism.user = "自己";
					}
					criticism.content = content;
					Intent intent = new Intent();
					intent.putExtra("criticism", criticism);
					setResult(0, intent);
					handler.sendEmptyMessage(Constant.MESSAGE_SEND_OK);
					finish();
				} else {
					setResult(-1);
					handler.sendEmptyMessage(Constant.MESSAGE_SEND_ERR);
					finish();
				}
			}

		});
		if (isSinaBind) {
			ThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					PSCTUtil.saveShareImage(getApplicationContext(), imagePathList);
					String picPath = getFileStreamPath("shared.jpg").getAbsolutePath();
					sm.getSinaAccount().sendMessage(getApplicationContext(), content, picPath,new SendResultListener() {

						@Override
						public void onSendOK() {
							toastOnUI("新浪微博同步完成");
							
						}

						@Override
						public void onSendErr(String msg) {
							toastOnUI(msg);
							
						}

						@Override
						public void onNetErr() {
							toastOnUI("网络异常");
							
						}});
				}

			});
		}
		if(isTenceBind) {
			ThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					PSCTUtil.saveShareImage(getApplicationContext(), imagePathList);
					String picPath = getFileStreamPath("shared.jpg").getAbsolutePath();
					sm.getTenceAccount().sendMessage(getApplicationContext(), content, picPath,new SendResultListener() {

						@Override
						public void onSendOK() {
							toastOnUI("腾讯微博同步完成");
							
						}

						@Override
						public void onSendErr(String msg) {
							toastOnUI(msg);
							
						}

						@Override
						public void onNetErr() {
							toastOnUI("网络异常");
							
						}});
				}

			});
		}

	}


	/**
	 * 在UI线程toast提示
	 * @param string
	 */
	private void toastOnUI(final String string) {
		this.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
				
			}
			
		});
		
	}
	@Override
	protected void onDestroy() {
		if(progress!=null&&progress.isShowing()) {
			progress.dismiss();
			progress=null;
		}
		super.onDestroy();
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		tvLimit.setText(count + "/120");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_send:
			String content = etContent.getText().toString();
			if (checkText(content))
				send(content);
			break;
		case R.id.iv_sina:
			if (isSinaBind) {
				isSinaBind = false;
				ivSina.setImageResource(R.drawable.sina_ico_unbind);
			} else {
				if(sm.isSinaBinded()) {
					isSinaBind=true;
					ivSina.setImageResource(R.drawable.sina_ico);
					return;
				}
				sm.bindingSina(AddCriticismActivity.this,new OnBindListener() {

					@Override
					public void onBind() {
						isSinaBind = true;
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								ivSina.setImageResource(R.drawable.sina_ico);
							}
						});
					}
				});
			}
			break;

		case R.id.iv_tence:
			if (isTenceBind) {
				isTenceBind = false;
				ivTence.setImageResource(R.drawable.tence_ico_unbind);

			} else {
				if(sm.isTenceBinded()) {
					isTenceBind=true;
					ivTence.setImageResource(R.drawable.tence_ico);
					return;
				}
				sm.bindingTence(AddCriticismActivity.this,new OnBindListener() {

					@Override
					public void onBind() {
						isTenceBind = true;
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								ivTence.setImageResource(R.drawable.tence_ico);
							}
						});
					}
				});
			}
			break;
		}

	}

	/**
	 * 检查内容是否合法23
	 * 
	 * @return
	 */
	private boolean checkText(String content) {

		if (TextUtils.isEmpty(content)) {
			Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		sm.handlActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

}
